package com.github.yoojia.flow.support;

import com.github.yoojia.flow.Context;
import com.github.yoojia.flow.Event;
import com.github.yoojia.flow.VirtualDevice;
import com.parkingwang.lang.data.Config;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author 陈小锅 (yoojiachen@gmail.com)
 * @since 1.0.0
 */
public abstract class VirtualScheduleDevice extends VirtualDevice {

    public static final String TOPIC = "SCHEDULERS";

    private final Timer mTimer = new Timer("SchedulerDevice", true);

    @Override
    public void onInit(Context context, Config configs) throws Exception {
        super.onInit(context, configs);
    }

    @Override
    public void onStart() {
        final long period = getInitConfig().getInt("period", 1000);
        final long delay = getInitConfig().getInt("delay", 0);
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                onScheduleTask();
            }
        }, delay, period);
    }

    @Override
    public void onStop() {
        mTimer.purge();
        mTimer.cancel();
    }

    @Override
    public Event handleEvent(Context context, Event request) {
        return Event.simple(request.sequence, Context.TOPIC_SYS_NORESP);
    }

    protected abstract void onScheduleTask();
}
